package vip.xiaonuo.common.util;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;

/**
 * @author zjt
 * @description 身份证号工具类
 * @date 2024/12/18 17:03
 */
public class CommonCardIDUtil {

    public static int getSexByIdCard(String idCard) {
        if (CommonStringFormatUtil.isValidCardId(idCard)) {
            char genderCode = idCard.charAt(16);
            if ((genderCode - '0') % 2 != 0) {
                return 1;
            } else {
                return 2;
            }
        }
        return 0;
    }

    public static int getAgeByIdCard(String idCard) {
        if (CommonStringFormatUtil.isValidCardId(idCard)) {
            // 提取出生年月日
            String birthStr = idCard.substring(6, 14);
            // 转换为日期
            try {
                int year = Integer.parseInt(birthStr.substring(0, 4));
                int month = Integer.parseInt(birthStr.substring(4, 6));
                int day = Integer.parseInt(birthStr.substring(6, 8));
                // 创建出生日期
                LocalDate birthDate = LocalDate.of(year, month, day);
                // 获取当前日期
                LocalDate now = LocalDate.now();

                // 计算年龄
                long age = ChronoUnit.YEARS.between(birthDate, now);

                // 如果今天是生日或者生日已过，则年龄加1
                if (now.getMonthValue() > month || (now.getMonthValue() == month && now.getDayOfMonth() >= day)) {
                    age++;
                }
                return (int) age;
            } catch (NumberFormatException | DateTimeParseException e) {
                // 转换失败，可能是日期格式不正确
                return -1;
            }
        }
        return -1; // 身份证号码无效
    }

    public static int getAgeByBirth(String birth) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate birthDate = LocalDate.parse(birth, formatter);
        LocalDate currentDate = LocalDate.now();
        Period period = Period.between(birthDate, currentDate);
        return period.getYears();
    }
}
